package com.iqiyi.pps.epg.core.service.sginal;

import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.model.web.sginal.TSginalStatus;
import com.iqiyi.pps.epg.api.model.web.sginal.TSginalStatusDataPage;
import com.iqiyi.pps.epg.core.dao.base.Page;
import com.iqiyi.pps.epg.core.dao.base.PropertyFilter;
import com.iqiyi.pps.epg.core.dao.sginal.SginalStatusDataDao;
import com.iqiyi.pps.epg.core.model.sginal.SginalStatus;
import com.iqiyi.pps.epg.core.utils.TransUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangjing on 2017/7/24.
 */
@Service
@Transactional
public class SginalStatusServiceImpl implements SginalStatusService {

    private Logger logger = LoggerFactory.getLogger(SginalStatusServiceImpl.class);

    @Autowired
    private SginalStatusDataDao dao;

    @Override
    public SginalStatus get(long id) {
        return dao.get(id);
    }

    @Override
    public long add(SginalStatus entity) {
        dao.saveOnly(entity);
        return entity.getId();
    }

    @Override
    public void update(SginalStatus entity) {
        dao.save(entity);
    }

    @Override
    public TSginalStatusDataPage getSginalStatusData(TPage page, TFilter filter) {
        Map<String, String> map = filter.getFilters();
        String tempPattern = "${PARAMS}";
        String totalPattern = "select COUNT(*)";
        List<PropertyFilter> filterList = TransUtil.builderFilterList(filter);
        String hql = tempPattern + " from com.iqiyi.pps.epg.core.model.sginal.SginalStatus";
        Page<SginalStatus> dbPage = TransUtil.buildPage(page);

        hql = TransUtil.buildQueryStringByPropertyFilter(dbPage, hql, filterList);

        if (dbPage.isAutoCount()) {
            String totalCount = dao.getSession().createQuery(hql.replace(tempPattern, totalPattern)).uniqueResult().toString();
            page.setTotalCount(Long.valueOf(totalCount));
        }

        List result = dao.getSession().createQuery(hql.replace(tempPattern, ""))
                .setMaxResults(dbPage.getPageSize())
                .setFirstResult((dbPage.getPageNo() - 1) * dbPage.getPageSize())
                .list();
        TSginalStatusDataPage tSginalStatusDataPage = new TSginalStatusDataPage();
        tSginalStatusDataPage.setTPage(page);
        List<TSginalStatus> tSginalStatusDatas = new ArrayList<TSginalStatus>();
        for(Object obj : result) {
            SginalStatus sginalStatus = (SginalStatus) obj;
            tSginalStatusDatas.add(sginalStatus.convertThriftModel());
        }
        tSginalStatusDataPage.setResult(tSginalStatusDatas);
        return tSginalStatusDataPage;
    }
}
